<template>
	<el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
		<el-form-item label="模板名称" prop="name">
			<el-input v-model="form.name"></el-input>
		</el-form-item>
		<el-form-item label="模板内容" prop="content">
			<div class="editor-container">
				<json-editor-vue class="editor" v-model="form.modContent" :show-btns="false" @focus="focusEditor" />
			</div>
		</el-form-item>
		<el-form-item>
			<el-button type="primary" @click="reset()">重置</el-button>

			<el-button type="primary" @click="saveEdit(formRef)">保 存</el-button>
		</el-form-item>
	</el-form>
</template>

<script lang="ts" setup>
import { ElMessage, FormInstance, FormRules, UploadProps } from 'element-plus';
import { ref } from 'vue';
// 引入vue-json-editor模块
import mod from '../api/mod'
import JsonEditorVue from 'json-editor-vue3'


const props = defineProps({
	data: {
		type: Object,
		required: true
	},
	edit: {
		type: Boolean,
		required: false
	},
	update: {
		type: Function,
		required: true
	}
});

const defaultData = {
	id: '',
	name: '',
	modContent: '',
};

const validateErr = ref(true);
const jsonEditor = ref();
const old_jsondata = ref(props.edit ? props.data.modContent : {});

const form = ref({ ...(props.edit ? props.data : defaultData) });

const rules: FormRules = {
	name: [{ required: true, message: '模板名称', trigger: 'blur' }],
	content: [{ required: true, message: '模板内容', trigger: 'blur' }]

};
const formRef = ref<FormInstance>();
const saveEdit = (formEl: FormInstance | undefined) => {
	commit();
	console.log(form.value);
};

// json重置
const reset = () => {
	form.value.modContent = old_jsondata.value;
};

// json 保存
const commit = async () => {

	if (!jsonEditor.value) {
		props.update();
		return;
	}
	const res = await jsonEditor.value.validate();
	validateErr.value = res.length > 0;

	if (!validateErr.value) {
		mod.save(
			form.value,
			(res) => {
				if (res.code === 200) {
					console.log(res)
					ElMessage.success('保存成功！');
					props.update();
				} else {
					ElMessage.success('保存失败！');
					props.update();
				}
			});

		validateErr.value = true;
	} else {
		props.update();
	}

};

const focusEditor = async (editor) => {
	console.log("focus")
	jsonEditor.value = editor;
}
</script>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}

.editor-container {
	width: 1000px;

}

.editor {
	padding: 0px;
}

.editor :deep(.jsoneditor-poweredBy) {
	display: none;

}
</style>
